package com.aiti.lulian.service.impl;

import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.uuid.UUIDUtil;
import com.aiti.lulian.dto.CardTemplateStyleDto;
import com.aiti.lulian.entity.CardTemplateBackground;
import com.aiti.lulian.entity.CardTemplateStyle;
import com.aiti.lulian.entity.CardTemplateStyleField;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardTemplateStyleMapper;
import com.aiti.lulian.service.CardTemplateBackgroundService;
import com.aiti.lulian.service.CardTemplateStyleFieldService;
import com.aiti.lulian.service.CardTemplateStyleService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.vo.CardTemplateStyleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class CardTemplateStyleServiceImpl extends ServiceImpl<CardTemplateStyleMapper, CardTemplateStyle> implements CardTemplateStyleService {

    @Autowired
    private CardTemplateStyleFieldService cardTemplateStyleFieldService;

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;

    @Autowired
    private ILuLianEnterpriseUserService luLianService;

    @Autowired
    private CardTemplateBackgroundService templateBackgroundService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message saveStyle(CardTemplateStyle cardTemplateStyle) {
        this.save(cardTemplateStyle);
        List<CardTemplateStyleField> fieldList = cardTemplateStyle.getFieldList();
        if(!CollectionUtils.isEmpty(fieldList)){
            fieldList.forEach(f->{
                f.setStyleId(cardTemplateStyle.getBaseId());
                f.setBaseCreateTime(new Date());
                f.setTemplateType(cardTemplateStyle.getTemplateType());
            });
            cardTemplateStyleFieldService.saveBatch(fieldList);

        }
        List<String> selectedBackgroundIdList = cardTemplateStyle.getSelectedBackgroundIds();
        if(!CollectionUtils.isEmpty(selectedBackgroundIdList)){
            LambdaUpdateWrapper<CardTemplateBackground> backgroundWrapper = new LambdaUpdateWrapper<>();
            backgroundWrapper.set(CardTemplateBackground::getVersion, cardTemplateStyle.getVersion()).set(CardTemplateBackground::getStyleId, cardTemplateStyle.getBaseId()).set(CardTemplateBackground::getTemplateType, cardTemplateStyle.getTemplateType()).in(CardTemplateBackground::getBaseId, selectedBackgroundIdList);
            templateBackgroundService.update(backgroundWrapper);
        }


        return Message.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message updateStyle(CardTemplateStyle cardTemplateStyle) {
        this.updateById(cardTemplateStyle);
        List<CardTemplateStyleField> fieldList = cardTemplateStyle.getFieldList();
        if(!CollectionUtils.isEmpty(fieldList)){
            cardTemplateStyleFieldService.remove(new LambdaQueryWrapper<CardTemplateStyleField>().eq(CardTemplateStyleField::getStyleId, cardTemplateStyle.getBaseId()).isNull(CardTemplateStyleField::getTemplateId));
            fieldList.forEach(f->{
                f.setStyleId(cardTemplateStyle.getBaseId());
                f.setBaseUpdateTime(new Date());
                f.setTemplateType(cardTemplateStyle.getTemplateType());
            });
            cardTemplateStyleFieldService.saveBatch(fieldList);
        }
        List<String> selectedBackgroundIdList = cardTemplateStyle.getSelectedBackgroundIds();
        if(!CollectionUtils.isEmpty(selectedBackgroundIdList)){
            LambdaUpdateWrapper<CardTemplateBackground> backgroundWrapper = new LambdaUpdateWrapper<>();
            backgroundWrapper.set(CardTemplateBackground::getVersion, cardTemplateStyle.getVersion()).set(CardTemplateBackground::getStyleId, cardTemplateStyle.getBaseId()).set(CardTemplateBackground::getTemplateType, cardTemplateStyle.getTemplateType()).in(CardTemplateBackground::getBaseId, selectedBackgroundIdList);
            templateBackgroundService.update(backgroundWrapper);
        }
        return Message.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message deleteStyle(String id) {
        long count = cardTemplateStyleFieldService.count(new LambdaQueryWrapper<CardTemplateStyleField>().eq(CardTemplateStyleField::getStyleId, id).isNotNull(CardTemplateStyleField::getTemplateId));
        if(count > 0){
            return Message.fail("当前样式已经被使用了，不能删除");
        }

        this.removeById(id);
        cardTemplateStyleFieldService.remove(new LambdaQueryWrapper<CardTemplateStyleField>().eq(CardTemplateStyleField::getStyleId, id).isNull(CardTemplateStyleField::getTemplateId));
        templateBackgroundService.remove(new LambdaQueryWrapper<CardTemplateBackground>().eq(CardTemplateBackground::getStyleId, id).isNull(CardTemplateBackground::getTemplateId));
        return Message.success();
    }

    @Override
    public Message detail(String id, String templateId) {
        //String enterpriseId = getEnterpriseId(userId);
        CardTemplateStyle entity = this.getById(id);
        if(entity == null){
            throw new RuntimeException("样式不存在");
        }
        LambdaQueryWrapper<CardTemplateStyleField> cardTemplateStyleFieldLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(templateId)){
            cardTemplateStyleFieldLambdaQueryWrapper.eq(CardTemplateStyleField::getTemplateId, templateId);
        }else{
            cardTemplateStyleFieldLambdaQueryWrapper.isNull(CardTemplateStyleField::getTemplateId);
        }
        cardTemplateStyleFieldLambdaQueryWrapper.eq(CardTemplateStyleField::getStyleId, id).orderByAsc(CardTemplateStyleField::getBaseCreateTime);
        List<CardTemplateStyleField> fieldList = cardTemplateStyleFieldService.list(cardTemplateStyleFieldLambdaQueryWrapper);
//        if(CollectionUtils.isEmpty(fieldList)){
//            fieldList = cardTemplateStyleFieldService.list(new LambdaQueryWrapper<CardTemplateStyleField>().isNull(CardTemplateStyleField::getTemplateId).eq(CardTemplateStyleField::getStyleId, id).orderByAsc(CardTemplateStyleField::getBaseCreateTime));
//        }
        entity.setFieldList(fieldList);
        return Message.success(entity);
    }

    @Override
    public CardTemplateStyle styleDetail(String id, String templateId, String templateType) {
        //String enterpriseId = getEnterpriseId(userId);
        CardTemplateStyle entity = this.getById(id);
        if(entity == null){
            throw new RuntimeException("样式不存在");
        }
        LambdaQueryWrapper<CardTemplateStyleField> cardTemplateStyleFieldLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(templateId)){
            cardTemplateStyleFieldLambdaQueryWrapper.eq(CardTemplateStyleField::getTemplateId, templateId);
        }else{
            cardTemplateStyleFieldLambdaQueryWrapper.isNull(CardTemplateStyleField::getTemplateId);
        }
        cardTemplateStyleFieldLambdaQueryWrapper.eq(CardTemplateStyleField::getStyleId, id).eq(CardTemplateStyleField::getTemplateType, templateType).orderByAsc(CardTemplateStyleField::getBaseCreateTime);
        List<CardTemplateStyleField> fieldList = cardTemplateStyleFieldService.list(cardTemplateStyleFieldLambdaQueryWrapper);
        if(CollectionUtils.isEmpty(fieldList)){
            fieldList = cardTemplateStyleFieldService.list(new LambdaQueryWrapper<CardTemplateStyleField>().isNull(CardTemplateStyleField::getTemplateId).eq(CardTemplateStyleField::getStyleId, id).eq(CardTemplateStyleField::getTemplateType, templateType).orderByAsc(CardTemplateStyleField::getBaseCreateTime));
        }
        entity.setFieldList(fieldList);
        return entity;
    }

    @Override
    public Message preStyleList(Page page, CardTemplateStyleDto dto) {
        List<CardTemplateStyleVo> cardTemplateStyleVos = this.getBaseMapper().styleList(page, dto);
        PageResult rspData = new PageResult(
                cardTemplateStyleVos,
                new PageInfo(dto.getPageNum(), dto.getPageSize()),
                page.getTotal()
        );


        return Message.success(rspData);
    }

    @Override
    public Message enterpriseStyleList(Page page, CardTemplateStyleDto dto) {
        LambdaQueryWrapper<CardTemplateStyle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CardTemplateStyle::getVersion, dto.getVersion()).eq(StringUtils.isEmpty(dto.getTemplateType()),CardTemplateStyle::getTemplateType, dto.getTemplateType()).orderByDesc(CardTemplateStyle::getBaseCreateTime);
        Page<CardTemplateStyle> pageResult = this.page(page, wrapper);
        PageResult rspData = new PageResult(
                pageResult.getRecords(),
                new PageInfo(dto.getPageNum(), dto.getPageSize()),
                pageResult.getTotal()
        );
        return Message.success(rspData);
    }

    @Override
    public CardTemplateStyle getStyleById(String id, String templateId) {
        CardTemplateStyle entity = this.getById(id);
        if(entity == null){
            throw new RuntimeException("样式不存在");
        }
        LambdaQueryWrapper<CardTemplateStyleField> cardTemplateStyleFieldLambdaQueryWrapper = new LambdaQueryWrapper<>();

        cardTemplateStyleFieldLambdaQueryWrapper.eq(CardTemplateStyleField::getTemplateId, templateId).eq(CardTemplateStyleField::getStyleId, id).orderByAsc(CardTemplateStyleField::getBaseCreateTime);
        List<CardTemplateStyleField> fieldList = cardTemplateStyleFieldService.list(cardTemplateStyleFieldLambdaQueryWrapper);
        if(CollectionUtils.isEmpty(fieldList)){
            fieldList = cardTemplateStyleFieldService.list(new LambdaQueryWrapper<CardTemplateStyleField>().eq(CardTemplateStyleField::getStyleId, id).isNull(CardTemplateStyleField::getTemplateId).orderByAsc(CardTemplateStyleField::getBaseCreateTime));
        }

        entity.setFieldList(fieldList);
        return entity;
    }

    @Override
    public Message saveStyleBatch(List<CardTemplateStyle> list) {
        this.saveBatch(list);
        return Message.success();
    }



    private String getEnterpriseId(String userId){
        Message message = cloudShowManagerSubService.getUserInfo(userId);
        if (message == null) {
            throw new RuntimeException("查询用户信息错误！");
        }
        Object obj = message.getObj();
        if (obj == null) {
            throw new RuntimeException("查询用户信息错误！");
        }
        if (message.getCode() == 1) {
            throw new RuntimeException("查询用户信息错误！");
        }
        ObjectMapper mapper = new ObjectMapper();
        Map resultMap = mapper.convertValue(obj, Map.class);
        String enterpriseId = (String)resultMap.get("companyId");
        if(StringUtils.isEmpty(enterpriseId)){
            //查询当前公司
            LuLianEnterprise luLianEnterprise = luLianService.selectCurrentUserJoinEnterpriseInfo(userId);
            if(luLianEnterprise != null) {
                enterpriseId = luLianEnterprise.getBaseId();
            }
        }
        return enterpriseId;
    }

    @Override
    public CardTemplateStyle preStyleDetail(String id, String templateId, String templateType) {
        CardTemplateStyle entity = this.getById(id);
        if(entity == null){
            throw new RuntimeException("样式不存在");
        }
        LambdaQueryWrapper<CardTemplateStyleField> cardTemplateStyleFieldLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(templateId)){
            cardTemplateStyleFieldLambdaQueryWrapper.eq(CardTemplateStyleField::getTemplateId, templateId);
        }else{
            cardTemplateStyleFieldLambdaQueryWrapper.isNull(CardTemplateStyleField::getTemplateId);
        }
        cardTemplateStyleFieldLambdaQueryWrapper
        .eq(CardTemplateStyleField::getStyleId, id).eq(CardTemplateStyleField::getTemplateType, templateType).orderByAsc(CardTemplateStyleField::getBaseCreateTime);
        List<CardTemplateStyleField> fieldList = cardTemplateStyleFieldService.list(cardTemplateStyleFieldLambdaQueryWrapper);
        entity.setFieldList(fieldList);
        return entity;
    }

    @Override
    public CardTemplateStyle preDetail(String id, String templateType) {
        CardTemplateStyle entity = this.getById(id);
        if(entity == null){
            throw new RuntimeException("样式不存在");
        }
        if(!StringUtils.isEmpty(id)){
            LambdaQueryWrapper<CardTemplateStyleField> cardTemplateStyleFieldLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cardTemplateStyleFieldLambdaQueryWrapper
                    .eq(CardTemplateStyleField::getStyleId, id).eq(CardTemplateStyleField::getTemplateType, templateType).isNull(CardTemplateStyleField::getTemplateId).orderByAsc(CardTemplateStyleField::getBaseCreateTime);
            List<CardTemplateStyleField> fieldList = cardTemplateStyleFieldService.list(cardTemplateStyleFieldLambdaQueryWrapper);
            entity.setFieldList(fieldList);
//            LambdaQueryWrapper<CardTemplateBackground> backgroundWrapper = new LambdaQueryWrapper<>();
//            backgroundWrapper.eq(CardTemplateBackground::getStyleId, id).isNull(CardTemplateBackground::getTemplateId).isNull(CardTemplateBackground::getEnterpriseId);
//            List<CardTemplateBackground> backgroundList = templateBackgroundService.list(backgroundWrapper);
//            entity.setBackgroundList(backgroundList);
        }else{
            entity.setFieldList(new ArrayList());
            //entity.setBackgroundList(new ArrayList());
        }

        return entity;
    }


    @Override
    public Message styleList(Page page, CardTemplateStyleDto dto) {

        LambdaQueryWrapper<CardTemplateStyle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CardTemplateStyle::getVersion, dto.getVersion()).eq(StringUtils.isEmpty(dto.getTemplateType()),CardTemplateStyle::getTemplateType, dto.getTemplateType()).orderByDesc(CardTemplateStyle::getBaseCreateTime);
        Page<CardTemplateStyle> pageResult = this.page(page, wrapper);
        PageResult rspData = new PageResult(
                pageResult.getRecords(),
                new PageInfo(dto.getPageNum(), dto.getPageSize()),
                pageResult.getTotal()
        );
        return Message.success(rspData);
    }
}